package com.jss.lanouhn.fristapp.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jss.lanouhn.fristapp.R;
import com.jss.lanouhn.fristapp.adapters.CategorySampleSuperAdapter;
import com.jss.lanouhn.fristapp.adapters.SampleListViewAdapter;
import com.jss.lanouhn.fristapp.modles.CategorySampleInfo;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 实现单品页面的fragment
 * Created by lanouhn on 16/8/26.
 */
public class Category_Sample_Fragment extends Fragment {
    private String url = "http://api.liwushuo.com/v2/item_categories/tree";
    private ListView listView;
    private CategorySampleInfo sampleInfo;
    private RecyclerView rv;
    private CategorySampleSuperAdapter superAdapter;
    private LinearLayoutManager llManager;
//    private boolean isMove;
    private SampleListViewAdapter listViewAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_category_sample, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView = (ListView) getView().findViewById(R.id.lv_sample);
        rv = (RecyclerView) getView().findViewById(R.id.rc_categoty_sample);
        initForWeb();
        initEvent();
    }


    private void initForWeb() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(getContext(), "网络解析数据错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Gson gson = new Gson();
                        sampleInfo = gson.fromJson(result, CategorySampleInfo.class);
                        if (sampleInfo.getData().getCategories().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            Toast.makeText(getContext(), "网络请求错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    List<String> lists = new ArrayList<>();
//                    for (int i = 0; i < sampleInfo.getData().getCategories().size(); i++) {
//                        lists.add(sampleInfo.getData().getCategories().get(i).getName());
//                    }
//                    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, lists);
//                    listView.setAdapter(adapter);

                    listViewAdapter=new SampleListViewAdapter(getActivity(),sampleInfo);

                    listView.setAdapter(listViewAdapter);
                    llManager = new LinearLayoutManager(getContext());
                    rv.setLayoutManager(llManager);
                    superAdapter = new CategorySampleSuperAdapter(getContext(), sampleInfo);
                    rv.setAdapter(superAdapter);

                    break;
            }
        }
    };

    private void initEvent() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                listViewAdapter.setSelectItem(position);
                listViewAdapter.notifyDataSetChanged();
                //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
                int firstItem = llManager.findFirstVisibleItemPosition();
                int lastItem = llManager.findLastVisibleItemPosition();
                //然后区分情况
                if (position <= firstItem) {
                    //当要置顶的项在当前显示的第一个项的前面时
                    rv.scrollToPosition(position);
                } else if (position <= lastItem) {
                    //当要置顶的项已经在屏幕上显示时
                    int top = rv.getChildAt(position - firstItem).getTop();
                    rv.scrollBy(0, top);
                } else {
                    //当要置顶的项在当前显示的最后一项的后面时
                    rv.scrollToPosition(position);
                    //这里这个变量是用在RecyclerView滚动监听里面的

                }
            }
        });

        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("sample","就开始搭建");
                int n = llManager.findFirstVisibleItemPosition();
                Log.d("sample",n+"");
                listView.setSelection(n);
                listView.smoothScrollToPosition(n);

                listViewAdapter.setSelectItem(n);
                listViewAdapter.notifyDataSetChanged();
                //在这里进行第二次滚动（最后的100米！）

                    //获取最顶端的Item的下标
//                 int n=llManager.findFirstCompletelyVisibleItemPosition();
//                    int n = llManager.findFirstVisibleItemPosition();
//                    Log.d("sample",n+"");
//                    listView.setSelection(n);
//                    listView.smoothScrollToPosition(n);
//                    listViewAdapter.setSelectItem(n);
//                    listViewAdapter.notifyDataSetChanged();

            }
        });

    }

}
